const express = require('express');
const router = express.Router();
const {
	select
} = require("../../config/mysql")
// 数据库
let db = require('../../config/mysql');
const {
	getDate
} = require('../../config/tool')
/**
 * @api {get} /api/admin/order/list 获取所有账户订单列表
 * @apiDescription 获取系统中的订单列表，根据订单状态获取列表，具备分页功能
 * @apiName AdminOrderList
 * @apiGroup admin Order
 * @apiPermission admin
 * 
 * @apiParam {Number} [pageSize] 一个页有多少个商品,默认4个;
 * @apiParam {Number} [pageIndex] 第几页,默认1;
 * @apiParam {Number} [order_id] 根据id精准搜索
 * @apiParam {Number=0,3,4,5,all} status 订单状态:0-待付款，3-待发货，4-待收货，5-待评价，all-所有状态;
 *
 * @apiSampleRequest /api/admin/order/list
 */
router.get('/list', async function (req, res) {
	let {
		pageSize = 4, pageIndex = 1, status = 'all', order_id = ''
	} = req.query;
	let size = parseInt(pageSize);
	let count = size * (pageIndex - 1);
	// 查询所有订单
	const total = await select('select count(*) from orders')
	let sql =
		`SELECT o.id, o.create_time, o.payment, os.text AS status,order_state
		 FROM orders o JOIN order_status os ON o.order_state = os.CODE `;
	// 根据订单状态查询
	let hasSearch = false //判断是否有添加条件，用于判断是用where还是用and
	if (status != 'all') {
		sql += ` WHERE o.order_state = ${status}`;
		hasSearch = true
	}
	if (order_id !== '') {
		sql += ` ${hasSearch?'and':'where'} o.id = ${order_id}`
		hasSearch = true
	}

	sql += ' ORDER BY o.create_time DESC LIMIT ? OFFSET ?'
	db.query(sql, [size, count], function (results, fields) {
		// 查询订单商品信息
		let data = results;
		let sql =
			`SELECT g.id, o.id AS order_id, g.name, g.img_md, og.goods_num, og.goods_price
			 FROM orders o JOIN order_goods og ON o.id = og.order_id
			 JOIN goods g ON g.id = og.goods_id`;
		if (status != 'all') {
			sql += ` ${'where'} o.order_state = ${status}`;
			hasSearch = true;
		}

		db.query(sql, [], (results, fields) => {
			data.forEach((order) => {
				if (!order.goodsList) {
					order.goodsList = [];
				}
				results.forEach((goods) => {
					if (order.id == goods.order_id) {
						order.goodsList.push(goods);
					}
				});
			});
			//成功
			res.json({
				status: true,
				msg: "success!",
				data,
				total: Object.values(total[0])[0]
			});
		});
	});
});
/**
 * @api {get} /api/admin/order 获取订单详情
 * @apiName OrderDetail
 * @apiGroup admin Order
 * @apiPermission admin
 *
 * @apiParam {Number} id 订单id;
 *
 * @apiSampleRequest /api/admin/goods
 */
router.get("/", async function (req, res) {
	const {
		id,
	} = req.query;
	const {
		id: uid
	} = req.user
	const address = await select("SELECT a.*, p.`name` AS province_name, c.`name` AS city_name, ct.`name` AS county_name, t.`name` AS town_name FROM address a JOIN province p ON p.province_id = a.province_id JOIN city c ON c.city_id = a.city_id JOIN county ct ON ct.county_id = a.county_id JOIN town t ON t.town_id = a.town_id WHERE uid =? AND isDefault =1 LIMIT 1", [uid])
	let order = await select(`SELECT * FROM  orders o WHERE  id  = ${id}`)
	order = await order.AsyncMap(async e => {
		let goodsList = await select(`SELECT * FROM order_goods og  WHERE order_id = ${e.id}`)
		const userInfo = await select(`select * from user where id = ${e.uid}`)
		goodsList = await goodsList.AsyncMap(async e => {
			const goodsInfo = await select(`SELECT * FROM goods  WHERE id = ${e.goods_id}`)
			return {
				...e,
				...goodsInfo[0]
			}
		})
		return {
			...e,
			goodsList,
			userInfo: userInfo[0]
		}
	})
	res.json({
		status: true,
		msg: "success!",
		data: order[0],
		address: address[0]
	});
});
/**
 * @api {post} /api/admin/order/deliver 发货
 * @apiName OrderDeliver
 * @apiGroup admin Order
 * @apiPermission admin
 *
 * @apiParam {Number} id 订单id;
 * @apiParam {String} ship_name 快递公司;
 * @apiParam {Number} ship_number 快递单号;
 *
 * @apiSampleRequest /api/admin/goods
 */
router.post("/deliver", async function (req, res) {
	const {
		id,
		ship_name,
		ship_number
	} = req.body;
	let order = await select(`UPDATE orders  set order_state = 4,ship_name = '${ship_name}', ship_number = '${ship_number}' where id  = ${id}`)
	res.json({
		status: true,
		msg: "success!",
		data: order
	});
});
/**
 * @api {post} /api/admin/order/receiving 收货
 * @apiName OrderReceiving
 * @apiGroup admin Order
 * @apiPermission admin
 *
 * @apiParam {Number} id 订单id; 
 *
 * @apiSampleRequest /api/admin/goods 
 */
router.post("/receiving", async function (req, res) {
	const {
		id,
	} = req.body;
	let order = await select(`UPDATE orders  set order_state = 5,received_time = '${getDate()}' where id  = ${id}`)
	res.json({
		status: true,
		msg: "success!",
		data: order
	});
});
module.exports = router;